package vn.gq.udv.utils;


import java.io.File;

import vn.gq.udv.comic.AppStoreActivity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.webkit.WebView;
import android.widget.Toast;

public class UrlHandler {
	
	private Context mContext;
	
	public UrlHandler(Context context) {
		mContext = context;
	}
	
	
	public boolean appURLHandler(WebView webview, String url) {
		
		if (url.contains("http://")) {
			String state = Environment.getExternalStorageState();
			if (state.equals(Environment.MEDIA_MOUNTED)) {
				String downloadPath = Environment.getExternalStorageDirectory().getPath() + File.separator + "Download" + File.separator + String.valueOf(GQUtils.md5(url));
				File downloadFile = new File(downloadPath);
				if (!downloadFile.getParentFile().exists()) downloadFile.getParentFile().mkdirs();
				SimpleDownload client = new SimpleDownload(mContext);
				client.download(url, downloadPath, client.new OnDownloadCompleteListener() {
					
					@Override
					public void onComplete(String path) {
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
						startActivity(intent);
					}
				});
			}
		} else if (url.startsWith("market://")) {
			startMarket(url);
		} 
		return true;
	}
	
	public void startMarket(String uriString) {
		try {
			Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uriString));
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			mContext.startActivity(intent);
		} catch(ActivityNotFoundException e) {
			Toast.makeText(mContext, "Máy của bạn chưa cái ứng dụng Google Play", Toast.LENGTH_SHORT).show();
		}
	}
	
	public void startAppStoreActivity(String url) {
		Intent intent = new Intent(mContext, AppStoreActivity.class);
		intent.putExtra("URL", url);
		startActivity(intent);
	}
	
	public void startActivity(Intent intent) {
		try {
			mContext.startActivity(intent);
		} catch(ActivityNotFoundException e) {
		}
	}
}
